package com.ahrhyj.web.controller.common;

import com.ahrhyj.common.config.FastDFSClient;
import com.ahrhyj.common.core.domain.AjaxResult;
import com.ahrhyj.common.exception.CustomException;
import com.ahrhyj.common.exception.file.FileNameLengthLimitExceededException;
import com.ahrhyj.common.utils.StringUtils;
import com.ahrhyj.common.utils.file.FileUploadUtils;
import com.ahrhyj.common.utils.file.MimeTypeUtils;
import com.ahrhyj.system.domain.SysFastdfs;
import com.ahrhyj.system.service.ISysFastdfsService;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * fastdfs文件管理
 */
@Api(tags = "fastdfs文件管理")
@RestController
public class FastDFSController {
    @Autowired
    private FastDFSClient fastDFSClient;
    @Autowired
    private ISysFastdfsService sysFastdfsService;
    @Autowired
    private FdfsWebServer fdfsWebServer;

    @ApiOperation("文件上传")
    @PostMapping("/fastdfs/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, @RequestParam(value = "oldFileId", required = false) String oldFileId) throws Exception
    {
        if (file.isEmpty()) {
            return AjaxResult.error("上传的文件为空");
        }
        // 获取上传的文件名称，并结合存放路径，构建新的文件名称
        String filename = file.getOriginalFilename();
        String extension = FileUploadUtils.getExtension(file);

        int fileNamelength = filename.length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
        {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }


        FileUploadUtils.assertAllowed(file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        String filePath = null;
        try
        {
            filePath = fastDFSClient.uploadFile(file);
            SysFastdfs sysFastdfs = new SysFastdfs();
            sysFastdfs.setFileName(filename);
            sysFastdfs.setFileExtension(extension);

            String dfsPath = filePath.replace(fdfsWebServer.getWebServerUrl(), "");
            sysFastdfs.setFilePath(dfsPath);

            if (StringUtils.isNotBlank(oldFileId)){
                SysFastdfs oldFile = sysFastdfsService.selectSysFastdfsById(oldFileId);
                if (oldFile != null){
                    sysFastdfs.setId(oldFileId);
                    try {
                        fastDFSClient.deleteFile(oldFile.getFilePath());
                    } catch (Exception e) {
                    }
                    sysFastdfsService.updateSysFastdfs(sysFastdfs);
                }else {
                    sysFastdfsService.insertSysFastdfs(sysFastdfs);
                }
            }else{
                sysFastdfsService.insertSysFastdfs(sysFastdfs);
            }
            sysFastdfs.setFilePath(filePath);
            return AjaxResult.success(sysFastdfs);
        }
        catch (Exception e)
        {
            if (filePath != null){
                try {
                    fastDFSClient.deleteFile(filePath);
                } catch (Exception e1) {
                }

            }
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation("根据文件地址下载")
    @GetMapping("/fastdfs/download")
    public void downloadFile(String fileUrl, HttpServletRequest request, HttpServletResponse response) {
        fastDFSClient.downloadFile(fileUrl, request, response);
    }

    @ApiOperation("根据文件ID下载")
    @GetMapping("/fastdfs/downloadbyid")
    public void downloadFileById(String fastdfsId, HttpServletRequest request, HttpServletResponse response) {
        SysFastdfs sysFastdfs = sysFastdfsService.selectSysFastdfsById(fastdfsId);
        if (sysFastdfs == null){
            throw new CustomException("文件信息不存在");
        }
        fastDFSClient.downloadFile(sysFastdfs.getFilePath(), sysFastdfs.getFileName(), request, response);
    }
}
